// 定义路由节点的类型
type RouteNode = {
    name: string;
    path: string;
    alias?: string;
    disabled?: boolean;
    ancestors?: string[];
    children?: RouteNode[];
    icon?: string;
};

// 定义导入模块的类型
type ImportedModules = Record<string, () => Promise<unknown>>;

export const createApiRouter = (data: RouteNode | RouteNode[]) => {
    // 确保 data 是数组
    const routeData = Array.isArray(data) ? data : [data];
    // 导入视图模块
    const modules: ImportedModules = import.meta.glob("../views/**");

    const generateComponentPath = (ancestors: string[]): string => {
        return ancestors
            .map((item, index) =>
                index !== ancestors.length - 1 ? `${item}/` : `${item}.vue`
            )
            .join('');
    };

    return routeData.map((e: RouteNode) => {
        const { name, icon, alias, path, disabled, ancestors, children } = e;
        // 获取重定向路径
        const redirect = children && children.length > 0 ? children[0].path : undefined;
        // 生成组件路径
        const componentPath = ancestors && ancestors.length > 0
            ? generateComponentPath(ancestors)
            : null;
        // 获取组件
        const component = componentPath ? modules[`../views/${componentPath}`] : null;

        // 递归处理子节点
        const nestedChildren = children && children.length > 0
            ? createApiRouter(children)
            : [];

        if (ancestors) {
            return {
                name,
                path,
                redirect,
                // alias,
                meta: {
                    title: name,
                    icon: icon,
                    name: alias
                },
                ancestors,
                disabled,
                component,
                ...(nestedChildren.length > 0 && { children: nestedChildren }),
            };
        } else {
            return {
                name,
                path,
                meta: {
                    title: name,
                    icon: icon,
                    name: alias
                },
                // alias,
                redirect,
                ancestors,
                disabled,
                ...(nestedChildren.length > 0 && { children: nestedChildren }),
            };
        }
    });
};

